const fs = require('fs');
const Path = require('path');
const jpeg = require('jpeg-js');


class ImageTransfer {
    constructor(src) {
        this.result = '';
    }

    setImage(src) {
        if (!src || !fs.existsSync(src)) throw new Error('图片不存在!');
        this.file = src;
        this.red = [];
        this.green = [];
        this.blue = [];
        this.opacity = [];
        this.parseImage();
    }

    parseImage() {
        this.result = fs.readFileSync(this.file);
        this.imageData = jpeg.decode(this.result);
        for (let i = 0; i < this.imageData.data.length; i += 4) {
            this.red.push(this.imageData.data[i + 0]);
            this.green.push(this.imageData.data[i + 1]);
            this.blue.push(this.imageData.data[i + 2]);
            this.opacity.push(this.imageData.data[i + 3]);
        }
    }

    filterColor(color = 'blue') {
        const jpegImageData = jpeg.encode({
            data: this[color],
            width: this.imageData.width,
            height: this.imageData.height
        });

        this.result = jpegImageData.data;

        return jpegImageData.data;
    }

    transformToText() {
        const txtData = [];
        const x = this.imageData.height, y = this.imageData.width;

        const ascii = '*#@ABCDEFGHIJKLMNAabcdefghijklm[]{}_+-=~`*&^%$#@!';

        for (let i = 0; i < x; i++) {
            txtData[i] = [];
            for (let j = 0; j < y; j++) {
                const index = i * x + j;
                const value = parseInt(this.green[index] / 100);
                txtData[i].push(ascii[value]);
            }
        }

        // console.log(txtData.length);

        let text = '';

        for (let r = 0; r < txtData.length; r++) {
            const line = txtData[r].join('');
            text += line + '\n';
        }

        this.result = text;

        return this;
    }

    save(path) {
        let outPath = Path.resolve(__dirname, './output');
        if (!path) {
            const filename = Path.basename(this.file).split('.')[0];
            const extname = Path.extname(this.file);
            outPath += `/${filename}-t${extname}`;
        }
        console.log(outPath)
        const writeStream = fs.createWriteStream(outPath);
        return new Promise((resolve, reject) => {
            writeStream.write(this.result, (err) => {
                if (err) reject(err);
                resolve(path);
            });
        });
    }
}

module.exports = ImageTransfer;